package com.ruoyi.web.controller.gift;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
public class FileUploadController {

    @Value("${kk.path}") // 使用Spring框架的注解@Value获取（参数一般都是EL表达式），配置文件中规定的上传目录;
    private String  uploadDirectory; // 将注解获取的上传目录，保存在uploadDirectory变量中;

    @PostMapping("/upload/image")
    @CrossOrigin // 支持跨域;
    public ResponseEntity<String> uploadImage(@RequestParam("image") MultipartFile image) {
        // 接收上传文件的类型为 MultipartFile;
        if (image.isEmpty()) {
            return ResponseEntity.badRequest().body("请选择要上传的文件");
        }

        try {
            // 保存文件到指定目录
            String fileName = image.getOriginalFilename();
            String upFileDate = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss").format(new Date());
            Path filePath = Paths.get(uploadDirectory + upFileDate + fileName);
            Files.copy(image.getInputStream(), filePath);

            // 返回文件访问URL
            String fileUrl = "http://192.168.208.1:8080/image?imageName=" + upFileDate + fileName; // 修改为你的文件访问URL
            return ResponseEntity.ok().body("{\"url\": \"" + fileUrl + "\"}");
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body("文件上传失败: " + e.getMessage());
        }
    }
}